<?php
namespace ZyucMini\Components\Expert\Services;

use ZyucMini\Components\Connections\Connections;
use ZyucMini\Components\Expert\Models\Task AS TaskModel;
use ZyucMini\Components\Expert\Models\TaskHandle AS TaskHandleModel;

class Task {

    protected $task_model;
    protected $task_handle_model;

    public function __construct() {
        Connections::initAll();
    }

    private function getTaskModel() {
        if(!$this->task_model) {
            $this->task_model = new TaskModel();
        }
        $this->task_model->newQuery();
        return $this->task_model;
    }
    

    /**
     * 获取一周的任务列表
     */
    public function getWeekTask() {
        $rows = $this->getTaskModel()->getTaskByWeek();
        $finishId = [];
        foreach ($rows as $row) {
            if ($row['is_finish']) {
                $finishId[] = $row['id'];
            }
        }
        $handleModel = new TaskHandleModel();
        $finishs = $handleModel->getFinishListByTasks($finishId);
        foreach ($rows as &$row) {
            $row['handle_text'] = $finishs[$row['id']] ?? '未完成';
        }
        return $rows;
    }

    // 查询某个专家的任务数量
    public function getTaskCountsByUser($userId) {
        $completed = $this->getTaskModel()->getCompleteds();
        $completed_count = $completed->where('task_handle', '=', $userId)->count();
        $ongoing = $this->getTaskModel()->getInProgress();
        $ongoing_count = $ongoing->where('task_handle', '=', $userId)->count();
        return [
            'total_tasks' => ($completed_count + $ongoing_count),
            'completed_tasks' => $completed_count,
            'ongoing_tasks' => $ongoing_count,
        ];
    }
    
}
?>